package test.edu.demo.AnnotationConfigApplicationContext;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

/**
 * @author xiao.hu
 * @date 2021-08-07
 * @apiNote  @ConfigurationProperties 读取配置文件，声明一个类是读取配置类
 *           Junit测试环境下@PropertySource只能读取 *.properties 形式的配置文件
 */
@PropertySource("classpath:application-dev.properties")
public class JdbcProperties {
    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Bean("dataSource")
    public DataSource dataSource() {
        HikariDataSource datasource = new HikariDataSource();
        if(this.url == null) {
            return datasource;
        }
        datasource.setJdbcUrl(this.url);
        datasource.setDriverClassName(this.driverClassName);
        datasource.setUsername(this.username);
        datasource.setPassword(this.password);
        return datasource;
    }

    @Override
    public String toString() {
        return String.format("url: %s, driverClassName: %s, username: %s, password: %s",
                url, driverClassName, username, password);
    }

    public String getUrl() {
        return url;
    }


    public String getDriverClassName() {
        return driverClassName;
    }

    public String getUsername() {
        return username;
    }


    public String getPassword() {
        return password;
    }

}
